#version 450 core

layout(location = 0) in vec3 positionOS;

uniform mat4 viewMatrix;
uniform mat4 projMatrix;
uniform float tf;

out vec4 varyingColor;

mat4 buildRotateX(float rad);
mat4 buildRotateY(float rad);
mat4 buildRotateZ(float rad);
mat4 buildTranslate(float x, float y, float z);

void main()
{
    float i = gl_InstanceID + tf;
    float a = sin(203.0 * i / 8000.0) * 403.0;
    float b = sin(301.0 * i / 4001.0) * 401.0;
    float c = sin(400.0 * i / 6003.0) * 405.0;
    mat4 localRotX = buildRotateX(1.75 * i);
    mat4 localRotY = buildRotateY(1.75 * i);
    mat4 localROtZ = buildRotateZ(1.75 * i);
    mat4 localTrans = buildTranslate(a, b, c);
    mat4 modelMatrix = localTrans * localRotX * localRotY * localROtZ;
    mat4 mvMatrix = viewMatrix * modelMatrix;
    gl_Position = projMatrix * mvMatrix * vec4(positionOS, 1.0);
    varyingColor = vec4(positionOS * 0.5 + vec3(0.5, 0.5, 0.5), 1.0);
}

mat4 buildRotateX(float rad)
{
    mat4 mat = mat4(1.0, 0.0, 0.0, 0.0,
                0.0, cos(rad), sin(rad), 0.0,
                0.0, -sin(rad), cos(rad), 0.0,
                0.0, 0.0, 0.0, 1.0);
    return mat;
}

mat4 buildRotateY(float rad)
{
    mat4 mat = mat4(0.0, cos(rad), -sin(rad), 0.0,
                    1.0, 0.0, 0.0, 0.0,
                    0.0, sin(rad), cos(rad), 0.0,
                    0.0, 0.0, 0.0, 1.0);
    return mat;
}

mat4 buildRotateZ(float rad)
{
    mat4 mat = mat4(0.0, cos(rad), sin(rad), 0.0,
                    0.0, -sin(rad), cos(rad), 0.0,
                    1.0, 0.0, 0.0, 0.0,
                    0.0, 0.0, 0.0, 1.0);
    return mat;
}

mat4 buildTranslate(float x, float y, float z)
{
    mat4 mat = mat4(1.0, 0.0, 0.0, 0.0,
                    0.0, 1.0, 0.0, 0.0,
                    0.0, 0.0, 1.0, 0.0,
                    x, y, z, 1.0);
    return mat;
}